<?php

namespace app\common\service;

use app\common\exception\ApiException;
use app\common\model\Dept;
use app\common\model\Order;
use app\common\model\OrderBalanceLog;
use app\common\model\OrderBoard;
use app\common\model\OrderBoardItem;
use app\common\model\OrderException;
use app\common\model\OrderLogisticsLog;
use app\common\model\OrderTrip;
use app\common\model\User;
use app\common\utils\Image;
use app\common\utils\Is;
use app\common\validate\OrderValidate;
use taoser\exception\ValidateException;
use think\facade\Db;

class OrderService
{
    
    // 详情
    public static function detail($id = 0)
    {
        $deptId = UserService::getValue('dept_id');
        $orderInfo = Order::with(['insure', 'dept', 'end_dept'])->append(['pay_type_text', 'shipper_type_text'])->find($id)->toArray();
        if (strpos($orderInfo['contract'], 'http://sc.dm.ccjwcm.com') !== false) {
            $orderInfo['contract'] = str_replace('http://sc.dm.ccjwcm.com', 'http://admin.nmshicheng.com', $orderInfo['contract']);
        }
        $boardId = OrderBoardItem::where('dept_id','=',$deptId)->where('order_id','=',$orderInfo['id'])->value('board_id'); 
        $orderInfo['board'] = OrderBoard::where('id',$boardId)->find();
        return $orderInfo; 
    }

    /**
     * 订单全部详情
     * @param $id
     * @return void
     */
    public static function getDetail($id = 0)
    {
        $orderInfo = Order::with(['insure', 'dept', 'end_dept','logisticsLog', 'trips' => function ($query_a) {
            $query_a->with(['startDept','nowDept','endDept']);
        }, 'boardItem' => function ($query_b) {
            $query_b->with(['board','startDept','dept','endDept','nextDept']);
        }])->find($id)->toArray();
        if (strpos($orderInfo['contract'], 'http://sc.dm.ccjwcm.com') !== false) {
            $orderInfo['contract'] = str_replace('http://sc.dm.ccjwcm.com', 'http://admin.nmshicheng.com', $orderInfo['contract']);
        }
        return $orderInfo;
    }
    
    /**
     * 创建订单
     * @param $data
     * @return void
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function create($data)
    {
        try {
            validate(OrderValidate::class)->check($data);
        } catch (ValidateException $e) {
            throw new ApiException($e->getMessage());
        }
        
        $userInfo = UserService::get();
        $deptInfo = Dept::where('id', $userInfo->dept_id)->find();
        $endDept = Dept::where('id', $data['end_dept'])->find();
        
        if (empty($endDept)) {
            throw new ApiException('未找到该公司');
        }
        
        if (empty($data['contract'])) {
            throw new ApiException('请生成合同');
        }
        
        Db::startTrans();
        try {
            $order = new Order();
            $order->order_sn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $order->commission = !empty($data['commission']) ? $data['commission'] : 0;
            $order->remark = $data['remark'];
            $order->dept_id = $deptInfo->id;
            $order->end_dept_id = $endDept->id;
            
            $order->address = $data['address'];
            if(!empty($data['latitude'])){
                $order->latitude = $data['latitude'];
            }
            if(!empty($data['longitude'])){
                $order->longitude = $data['longitude'];
            }
            
            $order->end_address = $data['end_address'];
            if(!empty($data['end_latitude'])){
                $order->end_latitude = $data['end_latitude'];
            }
            if(!empty($data['end_longitude'])){
                $order->end_longitude = $data['end_longitude'];
            }
            if(isset($data['car_remark']) && !empty($data['car_remark'])){
                $order->car_remark = $data['car_remark'];
            }
            if(!empty($data['collection_car_type'])){
                $order->collection_car_type = $data['collection_car_type'];
            } else {
                $order->collection_car_type = 0;
            }
            
            $order->nickname = $userInfo['nickname'];
            $order->user_id = $userInfo->id;
            $order->shipper_mobile = $data['shipper_mobile'];
            $order->shipper_name = $data['shipper_name'];
            $order->shipper_type = $data['shipper_type'];
            $order->accept_mobile = $data['accept_mobile'];
            $order->accept_name = $data['accept_name'];
            $order->pay_type = $data['pay_type'];
            $order->total_price = $data['total_price'];
            $order->car_brand = $data['car_brand'];
            $order->car_shelf_num = $data['car_shelf_num'];
            $order->car_worth = $data['car_worth'];
            $order->car_color = $data['car_color'];
            $order->car_number = $data['car_number'];
            $order->insure_type = $data['insure_type'];
            $order->insure_price = $data['insure_price'];
            $order->contract = $data['contract'];
            $order->has_end_dept = $data['has_end_dept'];
            $order->eta = $data['eta'];
            $order->total_price1 = $data['total_price1'];
            $order->total_price2 = $data['total_price2'];
            $order->total_price3 = $data['total_price3'];
            $order->car_goods = $data['car_goods'];
            $order->car_other = $data['car_other'];
            
            //20240301调整为，下单就签合同
            $order->contract_status = 1;
            $order->status = 1;
            
            $order->save();
            $lastId = $order->getLastInsID();
            
            $orderTrip = new OrderTrip();
            $orderTrip->order_id = $lastId;
            $orderTrip->dept_id = $order->dept_id;
            $orderTrip->start_dept_id = $order->dept_id;
            $orderTrip->end_dept_id = $order->end_dept_id;
            $orderTrip->save();
            
            OrderLogisticsLog::setlog($lastId, '订单创建');
            
            // 现付
            // if ($data['pay_type'] == 2) {
            //     OrderBalanceLog::set(2, 3, $deptInfo->id, +$order['freight_price']);
            // }
            
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            throw new ApiException($exception->getMessage() . ':' . $exception->getLine());
        }
    }

    /**
     * 修改订单
     * @param $data
     * @return void
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function updateOrder($data)
    {
        try {
            validate(OrderValidate::class)->check($data);
        } catch (ValidateException $e) {
            throw new ApiException($e->getMessage());
        }
        
        $userInfo = UserService::get();
        $deptInfo = Dept::where('id', $userInfo->dept_id)->find();
        $endDept = Dept::where('id', $data['end_dept'])->find();
        
        if (empty($endDept)) {
            throw new ApiException('未找到该公司');
        }
        
        if (empty($data['contract'])) {
            throw new ApiException('请生成合同');
        }
        
        Db::startTrans();
        try {
            $order = Order::where('id', $data["id"])->find();
            $order->commission = !empty($data['commission']) ? $data['commission'] : 0;
            $order->remark = $data['remark'];
            $order->dept_id = $deptInfo->id;
            $order->end_dept_id = $endDept->id;
            
            $order->address = $data['address'];
            if(!empty($data['latitude'])){
                $order->latitude = $data['latitude'];
            }
            if(!empty($data['longitude'])){
                $order->longitude = $data['longitude'];
            }
            
            $order->end_address = $data['end_address'];
            if(!empty($data['end_latitude'])){
                $order->end_latitude = $data['end_latitude'];
            }
            if(!empty($data['end_longitude'])){
                $order->end_longitude = $data['end_longitude'];
            }
            if(!empty($data['collection_car_type'])){
                $order->collection_car_type = $data['collection_car_type'];
            } else {
                $order->collection_car_type = 0;
            }
            $order->shipper_mobile = $data['shipper_mobile'];
            $order->shipper_name = $data['shipper_name'];
            $order->shipper_type = $data['shipper_type'];
            $order->accept_mobile = $data['accept_mobile'];
            $order->accept_name = $data['accept_name'];
            $order->pay_type = $data['pay_type'];
            $order->total_price = $data['total_price'];
            $order->car_brand = $data['car_brand'];
            $order->car_shelf_num = $data['car_shelf_num'];
            $order->car_worth = $data['car_worth'];
            $order->car_color = $data['car_color'];
            $order->car_number = $data['car_number'];
            $order->insure_type = $data['insure_type'];
            $order->insure_price = $data['insure_price'];
            $order->contract = $data['contract'];
            $order->has_end_dept = $data['has_end_dept'];
            $order->eta = $data['eta'];
            $order->total_price1 = $data['total_price1'];
            $order->total_price2 = $data['total_price2'];
            $order->total_price3 = $data['total_price3'];
            $order->car_goods = $data['car_goods'];
            $order->car_other = $data['car_other'];
            
            $order->save();
            
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            throw new ApiException($exception->getMessage() . ':' . $exception->getLine());
        }
    }
    
    
    /**
     * 修改订单状态
     * @param $id tripId
     * @param $status
     * @param $data
     * @param $identity
     * @return \support\Response|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function update($id = 0, $status = 0, $data = [], $identity = 'start')
    {
        
        $orderTrip = OrderTrip::where('id', $id)->find();
        $deptInfo = Dept::where('id', $orderTrip->dept_id)->find();
        Db::startTrans();
        try {
            
            // 拍照验车
            if ($status === 1) {
                $orderTrip->inspect_status = $data['status'];
                if (!empty($data['photos'])) {
                    $orderTrip->photos = json_encode($data['photos']);
                }
                OrderLogisticsLog::setlog($orderTrip->order_id, $deptInfo['name'] . ' 拍照验车' . ($data['status'] == 1 ? '验车无异议' : '业务上报异常'));
                if ($data['status'] == 2) {
                    $orderTrip->exception_status = 1;
                }
                $status = 2;
            }
            
            // 入库可发
            if ($status === 2) {
                OrderLogisticsLog::setlog($orderTrip->order_id, $deptInfo['name'] . ' 入库可发');
            }
            
            // 客户取车 订单完结
            if ($status === 4) {
                $orderInfo = Order::find($orderTrip->order_id);
                if ($orderInfo->status != 4) {
                    $orderInfo->status = 4;
                    $orderInfo->finish_time = date("Y-m-d H:i:s");
                    $orderInfo->save();
                    OrderTrip::where('order_id', $orderInfo->id)->update(['status' => 4]);
                    OrderLogisticsLog::setlog($orderTrip->order_id, $deptInfo['name'] . ' 客户取车，订单完结');
                }
            }
            
            $orderTrip->status = $status;
            $orderTrip->save();
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return apiError($e->getMessage() . ':' . $e->getLine());
        }
    }
    
    /**
     * 获取配板发车列表
     * @return OrderTrip[]|array|\think\Collection|\think\db\Query[]|\think\model\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getOutList()
    {
        $deptId = UserService::getValue('dept_id');
        $list = OrderTrip::where([
            ['dept_id', '=', $deptId],
            ['status', '=', 2]
        ])->with(['orderinfo'])->select()->each(function ($item) {
            $item->start_dept_name = Dept::where('id', $item->start_dept_id)->value('name');
            $item->end_dept_name = Dept::where('id', $item->end_dept_id)->value('name');
        });
        // 始发站，改成坐标地址，
        // 终点站，改成坐标地址，那么就无法与终点站绑定
        return $list;
    }
    
    /**
     * 创建配板发车
     * @param $data
     * @return \support\Response|void
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createDeparture($data = [])
    {
        
        unset($data['other_remark']);
        
        $orders = $data['orders'];
        $nextId = 0;
        
        if(empty($data['is_end'])){
            $nextId = $data['next_dept_id']; 
        }
        
        $endDept = Dept::where('id', $nextId)->find();
        
        if (empty($orders)) {
            throw new ApiException('参数错误，请重试');
        }
        
        if ((!$data['driver_mobile'] || !$data['driver_name'] || !$data['license']) &&
            (!$data['company_name'] || !$data['company_mobile'] || !$data['company_nickname'])) {
            throw new ApiException('请输入司机内容或公司内容的其中之一');
        }
        
        if (!empty($data['driver_mobile']) && !Is::mobile($data['driver_mobile'])) {
            throw new ApiException('请输入正确手机号码');
        }
        
        if (!empty($data['company_mobile']) && !Is::mobile($data['company_mobile'])) {
            throw new ApiException('请输入正确手机号码');
        }
        
        $deptInfo = UserService::getDept();
        Db::startTrans();
        try {
            OrderTrip::where('order_id', 'in', array_map(fn($item) => $item['order_id'], $orders))->where('dept_id', $deptInfo['id'])->update(['status' => 3]);
            $orderlist = Order::where('id', 'in', array_map(fn($item) => $item['order_id'], $orders))->field('id,dept_id,end_dept_id')->select();
            // 创建下一站点的车辆数据
            foreach ($orderlist as $value) {
                if(!empty($data['is_end'])){
                    $value->end_dept_id = $deptInfo['id'];
                    $value->save();
                    OrderTrip::create(['order_id' => $value->id, 'dept_id' => $deptInfo->id, 'start_dept_id' => $value->dept_id, 'end_dept_id' => $deptInfo->id]);
                    // OrderTrip::where('order_id','=',$value['id'])->update(['end_dept_id'=>$deptInfo->id]);
                }else{
                    OrderTrip::create(['order_id' => $value->id, 'dept_id' => $nextId, 'start_dept_id' => $value->dept_id, 'end_dept_id' => $value->end_dept_id]);
                }
                if(!empty($endDept['name'])){
                    OrderLogisticsLog::setlog($value['id'], $deptInfo['name'] . '发车了，下一站：' .$endDept['name']);
                }else{
                    OrderLogisticsLog::setlog($value['id'], $deptInfo['name'] . '发车了');
                }
            }
            $data['dept_id'] = $deptInfo['id'];
            
            unset($data['orders']);
            unset($data['is_end']);
            $id = (new OrderBoard())->insertGetId($data);
            foreach ($orders as $value) {
                $orderInfo = Order::where('id',$value['order_id'])->find();
                OrderBoardItem::create([
                    'board_id' => $id,
                    'start_dept_id' => $orderInfo->dept_id,
                    'dept_id' => $deptInfo['id'],
                    'end_dept_id' => $orderInfo->end_dept_id,
                    'next_dept_id' => $nextId,
                    'order_id' => $value['order_id'],
                    'freight_price' => !empty($value['freight_price']) ? $value['freight_price'] : 0,
                    'fuel_price' => !empty($value['fuel_price']) ? $value['fuel_price'] : 0,
                    'handling_price' => !empty($value['handling_price']) ? $value['handling_price'] : 0,
                    'forklift_price' => !empty($value['forklift_price']) ? $value['forklift_price'] : 0,
                    'other_price' => !empty($value['other_price']) ? $value['other_price'] : 0,
                    'transfer_price' => !empty($value['transfer_price']) ? $value['transfer_price'] : 0,
                    'landing_price' => !empty($value['landing_price']) ? $value['landing_price'] : 0,
                    'total_price' => round($value['freight_price'], 2) +
                        round(floatval($value['fuel_price']), 2) +
                        round(floatval($value['handling_price']), 2) +
                        round(floatval($value['forklift_price']), 2) +
                        round(floatval($value['other_price']), 2) +
                        round(floatval($value['transfer_price']), 2) +
                        round(floatval($value['landing_price']), 2),
                    'create_time'   =>  date('Y-m-d H:i:s'),
                    'remarks' => $value["other_remark"]
                ]);
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ApiException($e->getMessage() . ':' . $e->getLine());
        }
    }
    
    
    // 生成新订单，发货
    public static function endpush($data = []){
        
        if ((!$data['driver_mobile'] || !$data['driver_name'] || !$data['license']) &&
            (!$data['company_name'] || !$data['company_mobile'] || !$data['company_nickname'])) {
            throw new ApiException('请输入司机内容或公司内容的其中之一');
        }
        if (!empty($data['driver_mobile']) && !Is::mobile($data['driver_mobile'])) {
            throw new ApiException('请输入正确手机号码');
        }
        if (!empty($data['company_mobile']) && !Is::mobile($data['company_mobile'])) {
            throw new ApiException('请输入正确手机号码');
        }
        $orderInfo = Order::where('id',$data['id'])->find();
        if(empty($orderInfo)){
            throw new ApiException('未找到该订单');
        }
        $deptId = UserService::getValue('dept_id');
        $id = (new OrderBoard())->insertGetId([
            'dept_id'   =>  $deptId,
            'next_dept_id'  =>  0,
            'driver_name'   =>  $data['driver_name'],
            'driver_mobile' =>  $data['driver_mobile'],
            'company_name'  =>  $data['company_name'],
            'company_mobile'=>  $data['company_mobile'],
            'company_nickname'  => $data['company_nickname'],
            'license'   =>  $data['license']
        ]);
        
        $freight_price = !empty($data['freight_price']) ? $data['freight_price'] : 0;
        $fuel_price = !empty($data['fuel_price']) ? $data['fuel_price'] : 0;
        $handling_price = !empty($data['handling_price']) ? $data['handling_price'] : 0;
        $forklift_price = !empty($data['forklift_price']) ? $data['forklift_price'] : 0;
        $other_price = !empty($data['other_price']) ? $data['other_price'] : 0;
        $transfer_price = !empty($data['transfer_price']) ? $data['transfer_price'] : 0;
        $landing_price = !empty($data['landing_price']) ? $data['landing_price'] : 0;
        
        OrderBoardItem::create([
            'board_id' => $id,
            'start_dept_id' => $deptId,
            'dept_id' => $deptId,
            'end_dept_id' => 0,
            'order_id' => $orderInfo->id,
            'freight_price' => $freight_price,
            'fuel_price' => $fuel_price,
            'handling_price' => $handling_price,
            'forklift_price' => $forklift_price,
            'other_price' => $other_price,
            'transfer_price' => $transfer_price,
            'landing_price' => $landing_price,
            'total_price' => round($freight_price, 2) +
                round($fuel_price, 2) +
                round($handling_price, 2) +
                round($forklift_price, 2) +
                round($other_price, 2)+
                round($transfer_price, 2) +
                round($landing_price, 2),
            'create_time'   =>  date('Y-m-d H:i:s')
        ]);
        
        $orderInfo->has_end_dept = 1;
        $orderInfo->save();
        
    }
    
    
    /**
     * 修改异常订单状态
     * @param $id
     * @param $status
     * @return void
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function updateExceptionStatus($id = 0, $status = 0)
    {
        $orderTrip = OrderTrip::where('id', $id)->find();
        $deptInfo = UserService::getDept();
        Db::startTrans();
        try {
            // if ($orderTrip['exception_status'] > 1) {
                // throw new ApiException('该异常状态已修改');
            // }
            if ($status === 2) {
                Order::where('id', $orderTrip->order_id)->update(['status' => 5]);
            }
            $orderTrip->save(['exception_status' => $status]);
            OrderLogisticsLog::setlog($orderTrip->order_id, $deptInfo['name'] . ($status === 1 ? '车辆已退回' : '继续托运'));
            Db::commit();
        } catch (\Exception $e) {
            
            
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }
    
    
    /**
     * 获取物流追踪数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getLogistics($id = 0)
    {
        $list = OrderLogisticsLog::where('order_id', $id)->select()->toArray();
        return $list;
    }
    
    /**
     * 获取指定运车站点信息
     * @param $id
     * @return array|mixed|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTrip($id = 0)
    {
        return OrderTrip::where('id', '=', $id)->find();
    }
    
    
    /**
     * @param $scene search || my.list,my.exception || dept.list,dept.exception
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getLists($scene = '', $options = [], $isExcel = false, $isCount = false)
    {
        $where = [];
        $whereOr = [];
        $isJoin = true;
        $sorts = "o.id desc";
        $field = 'o.*,ot.status as trip_status,ot.id as trip_id,ot.exception_status,ot.dept_id as current_dept_id';
        // 我的订单 参数status
        if ($scene === 'my.list') {
            $userInfo = UserService::get();
            $where[] = ['o.shipper_mobile|o.accept_mobile', '=', $userInfo['mobile']];
            $isJoin = false;
            $field = 'o.*';
            if (isset($options['status'])&&$options['status']) {
                $where[] = ['o.status', '=', $options['status']];
            }
        }
        
        // 我的异常订单 参数status
        if ($scene === 'my.exception') {
            $userInfo = UserService::get();
            $where[] = ['o.shipper_mobile', '=', $userInfo['mobile']];
            if (isset($options['status'])) {
                $where[] = ['ot.exception_status', '=', $options['status']];
            }
        }
        
        // 部门查询运单 参数keyword status identity
        if ($scene === 'dept.list') {
            $deptInfo = UserService::getDept();
            $where[] = ['ot.dept_id', '=', $deptInfo['id']];
            if (isset($options['status'])&&$options['status']!="") {
                $where[] = ['ot.status', '=', $options['status']];
            }
            if (!empty($options['keyword'])) {
                $where[] = ['o.car_shelf_num|o.shipper_name|o.shipper_mobile|o.accept_name|o.accept_mobile|o.address|o.end_address|o.car_brand|o.car_number', 'like', '%'.$options['keyword'].'%'];
            }
            if (!empty($options['identity'])) {
                // 始发单
                if ($options['identity'] === 'start') {
                    $where[] = ['ot.end_dept_id', 'exp', Db::raw('<> ot.dept_id')];
                    $where[] = ['ot.start_dept_id', 'exp', Db::raw('= ot.dept_id')];
                }
                // 中转单
                if ($options['identity'] === 'center') {
                    $where[] = ['ot.start_dept_id', 'exp', Db::raw('<> ot.dept_id')];
                    $where[] = ['ot.end_dept_id', 'exp', Db::raw('<> ot.dept_id')];
                    $sorts = "o.id asc";
                }
                // 终点单
                if ($options['identity'] === 'end') {
                    $where[] = ['ot.end_dept_id', 'exp', Db::raw('= ot.dept_id')];
                    $where[] = ['o.has_end_dept', '=', 1];
                    $sorts = "o.id asc";
                }
                
                if ($options['identity'] === 'noEnd') {
                    $where[] = ['ot.end_dept_id', 'exp', Db::raw('= ot.dept_id')];
                    $where[] = ['o.has_end_dept', '=', 0];
                    $sorts = "o.id asc";
                }
            }
            // 没有异常的单
            $where[] = ['ot.exception_status', 'not in', [1, 2]]; 
            
        }
        
        // 部门异常订单 参数status
        if ($scene === 'dept.exception') {
            $deptInfo = UserService::getDept();
            $where[] = ['ot.dept_id', '=', $deptInfo['id']];
            $where[] = ['o.status', 'not in', 4];
            $where[] = ['ot.exception_status', '>', 0]; 
            if (isset($options['status'])) {
                $where[] = ['ot.exception_status', '=', $options['status']]; 
            }
        }
        
        // 部门异常订单 参数status
        if ($scene === 'dept.contract') {
            $deptInfo = UserService::getDept();
            $where[] = ['ot.dept_id', '=', $deptInfo['id']];
            $where[] = ['o.status', '=', 0];
            if (isset($options['status'])) {
                $where[] = ['o.contract_status', '=', $options['status']];
            }
        }
        
        // 按照订单编号搜索运单
        if ($scene === 'search') {
            if (!empty($options['keyword'])) {
                $isJoin = false;
                $field = 'o.*';
                $where[] = ['o.order_sn', '=', $options['keyword']];
            }
        }
        
        if($scene === 'all'){
            $userInfo = UserService::get();
            if($userInfo['user_type'] === 1){ 
                if($userInfo['dept_id']){
                    $where[] = ['ot.dept_id', '=', $userInfo['dept_id']];
                }
            }else{
                // $where[] = ['o.shipper_mobile|o.accept_mobile', '=', $userInfo['mobile']];
            }
        }
        
        if($scene === 'adminAll'){
            $userInfo = UserService::get();
            $field = 'o.*,ot.status as trip_status,ot.id as trip_id,ot.exception_status,ot.dept_id as current_dept_id,ot.end_dept_id';

            // 数据权限
            $dataAuth = UserService::getRoleDataAuth($userInfo['id']);
            if (!empty($dataAuth)) {
                $whereOr = [
                    ['ot.start_dept_id', 'in', $dataAuth],
                    ['ot.dept_id', 'in', $dataAuth],
                    ['ot.end_dept_id', 'in', $dataAuth]
                ];
            }

            if(isset($options['orderStatus']) && !empty($options['orderStatus'])){
                $where[] = ['o.status', '=', $options['orderStatus']];
            }
            if(isset($options['start_dept_id']) && !empty($options['start_dept_id'])){
                $where[] = ['ot.start_dept_id', '=', $options['start_dept_id']];
            }
            if(isset($options['end_dept_id']) && !empty($options['end_dept_id'])){
                $where[] = ['ot.end_dept_id', '=', $options['end_dept_id']];
            }
            if(isset($options['dept_id']) && !empty($options['dept_id'])){
                $where[] = ['ot.dept_id', '=', $options['dept_id']];
            }
            if(isset($options['carStatus']) && !empty($options['carStatus'])){
                $where[] = ['ot.status', '=', $options['carStatus']];
            }
        }
        
        $timeBetween = request()->get('timeBetween',[]);
        if(!empty($timeBetween)){
            $timeBetween[1] = $timeBetween[1] . " 23:59:59";
            if ($options['timeType'] == 1) {
                $where[] = ['o.create_time','between',$timeBetween];
            } else if ($options['timeType'] == 2) {
                $where[] = ['ot.update_time','between',$timeBetween];
            } else if ($options['timeType'] == 3) {
                $where[] = ['o.finish_time','between',$timeBetween];
            }
//            $where[] = ['ot.create_time','between',$timeBetween];
        }
        
        $order = Order::alias('o')->with(['dept', 'end_dept']);
        if ($isJoin) {
            $order = $order->join('order_trip ot', 'ot.order_id = o.id', 'LEFT')->where(function ($query) use ($whereOr) {
                if(!empty($whereOr)){
                    $query->whereOr($whereOr);
                }
            });
        } 
        // print_r($options);exit;
        $list = $order->append(['status_text', 'pay_type_text','contract_text'])
            ->where($where)
            ->order($sorts)
            ->field($field);
            
        $res = null;
        if($isExcel === true){
            $res = $list->group("o.order_sn")->select();
        }else{
            if($isCount === true){
                $res = $list->count('o.id');
                return $res;
            }else{
                $res = $list->paginate();
            }
        }
        
        return $res->each(function ($item) {
            if (!empty($item->exception_status)) {
                $item->oe_status_text = OrderTrip::EXCEPTION_STATUS[$item->exception_status];
            }
            if (isset($item->trip_status)){  
                // 始发站
                if($item->current_dept_id === $item->dept_id){
                    $item->ot_status_text = OrderTrip::START_STATUS[$item->trip_status];
                }else if($item->current_dept_id === $item->end_dept_id){ 
                    $item->ot_status_text = OrderTrip::TERMINAL_START_STATUS[$item->trip_status];
                }else if($item->current_dept_id !== $item->end_dept_id && $item->current_dept_id !== $item->dept_id){
                    $item->ot_status_text = OrderTrip::TRANSFER_START_STATUS[$item->trip_status];
                }
            } 
            $item->start_dept_mobile = Dept::where('id', $item->dept_id)->value('mobile');
            // $item->freight_price = OrderBoardItem::alias('obi')->
            //     join('order_board ob','ob.id = obi.board_id','LEFT')->
            //     where('ob.next_dept_id', $item->dept_id)->
            //     where('obi.order_id', $item->order_id)->
            //     value('obi.freight_price');
            $deptInfo = UserService::getDept();
            if(!empty($deptInfo)){
                $item->freight_price = OrderBoardItem::alias('obi')->
                join('order_board ob','ob.id = obi.board_id','LEFT')->
                where('ob.next_dept_id', $deptInfo['id'])->
                where('obi.order_id', $item->id)->
                value('obi.freight_price');
            }else{
                $item->freight_price = 0;
            }
            
        });
    }
    
    public function createContract($data)
    {
        try {
            validate(OrderValidate::class)->scene('contract')->check($data);
        } catch (ValidateException $e) { 
            throw new ApiException($e->getMessage());
        }
        // $path = 'contract/' . date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . '.png';
        //
        // $path = 'contract/' . date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . '.png';
        // $filename = public_path() . '/upload/' . $path;
        $deptInfo = UserService::getDept();
        // // $endDeptInfo = Dept::where('id', $data['end_dept'])->find();
        // Image::merge(public_path() . '/upload/default/contract.jpg', $filename, ['text' => [
        //     [$data['shipper_name'], 170, 230],
        //     [$data['shipper_mobile'], 630, 230],
        //     [$data['address'], 170, 280],
        //     [$data['accept_name'], 170, 330],
        //     [$data['accept_mobile'], 630, 330],
        //     [$data['end_address'], 170, 380],
        //     [$data['car_brand'], 170, 430],
        //     [$data['car_number'], 630, 430],
        //     // 车辆识别码
        //     [$data['car_number'], 170, 480],
        //     // 数量
        //     [1, 630, 480],
        //     // 车价值
        //     [$data['car_worth'], 170, 580],
        //     // 保险费
        //     [$data['insure_price'], 630, 580],
        //     // 预付款
        //     [$data['total_price'], 170, 680],
        //     // 目的地结算
        //     [$data['total_price'], 630, 680],
        //     // 目的地结算
        //     // [$data['shipper_name'], 170, 1320, 50]
        // ]]);
        // return $path;
        //合同word模板
        $path = public_path() . '/upload/contract.docx';
        $uesrEg = date("YmdHis")."_".mt_rand(1, 99999);
        $nowPaymoney = 0; //预付款
        $endPaymoney = 0; //目的地结算
        if($data["pay_type"] == 1){ //到付
            $endPaymoney = $data["total_price"];
        }else if($data["pay_type"] == 2){ //现付
            $nowPaymoney = $data["total_price"];
        }
        $uData = [
            "shipperName" => $data["shipper_name"], //托运人
            "shipperMobile" => $data["shipper_mobile"], //托运人联系电话
            "address" => $data["address"], //始发地
            "acceptName" => $data["accept_name"], //收车人
            "acceptMobile" => $data["accept_mobile"], //收车人联系电话
            "endAddress" => $data["end_address"], //目的地
            "carDrand" => $data["car_brand"], //车型
            "carNumber" => $data["car_number"], //车牌号
            "carWorth" => $data["car_worth"], //车辆价值
            "carShelfNum" => $data["car_shelf_num"], //车架号
            "totalPrice" => $data["total_price"], //运输价格
            "totalPrice1" => !empty($data['total_price1']) ? $data['total_price1'] : "0 ",
            "totalPrice2" => !empty($data['total_price2']) ? $data['total_price2'] : "0 ",
            "totalPrice3" => !empty($data['total_price3']) ? $data['total_price3'] : "0 ",
            "collectionCarType" => $data["collection_car_type"]==1?'派送':'自提', 
            "carGoods" => !empty($data["car_goods"]) ? $data['car_goods'] : '', 
            "carOther" => !empty($data["car_other"]) ? $data['car_other'] : '', 
            "nowPaymoney" => $nowPaymoney, //运输价格
            "endPaymoney" => $endPaymoney, //运输价格
            "insurePrice" => !empty($data['insure_price']) ? $data['insure_price'] : "0 ", //保险费
            "payType" => $data["pay_type"],//付款方式
            "wordName" => config("app.public_path") . "/upload/contract/" . $uesrEg . '.docx',
            "createTime"=> date("Y年 m月 d日",time()),
            "deptMobile"=>$deptInfo['mobile'], //经办人电话
        ];
        $s = $this->getWord($uData, "1", $path);
        // echo $s;
        return $s;
    }

    /**
     * 生成word 并转换成图片
     *  $data输入模板数据array()
     *  $userId用户id
     *  $path模板路径,例子: root_path()."/public"
     */
    private function getWord($data, $userId, $path)
    {
        try {
            $word = new \app\api\controller\Pword(["save_path" => $data["wordName"]]);
            $imgUrl = $word->generateWordByTemplate($path, $data);
            $urlArr = explode('upload',$imgUrl);
            $lastImgUrl =  public_path().$urlArr[1];
            return  $urlArr[1];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
   
    public static function cancelOrder($id){
        if($id){
            OrderBoardItem::where('order_id',$id)->delete();
            OrderTrip::where('order_id',$id)->delete();
            // OrderBoard::where('id',$id)->delete();
            return Order::where('id',$id)->delete();
        }else{
            throw new ApiException('参数错误');
        }
    }
    
}